﻿/// <reference path="MGBusinessLayer.js" />



/**
* MSCRM 2016 Model Kit for JavaScript
* @author Mihir M. Kadam
* @current version : 1.0

* Credits:
*   The idea of this library was inspired by Jaimie Ji XrmServiceToolkit.
*   Additional thanks to all contributors of MSCRM and i have learned a lot from you all.
* Date: 31 July, 2016
*
* Special Thanks:
*   Somesh Siripuram (Sr.Developer at CloudFronts)
* Date: July, 2016

* What's new:
**********************************************************************************************************
*   Version: 1.0
*   Date: July, 2016
*       New Function - modelGeneration.BindData
*       New Function - modelGeneration.BindEvents
*       New Function - errorHandler
**********************************************************************************************************
*/


$(function () {
    BL.MG.FetchMasterData(modelGeneration.BindData, modelGeneration.errorHandler);

});


var modelGeneration = {
    data : {entityName:"",fileName:""},
    BindData: function (data) {
        /// <summary>
        /// Bind all data to HTML 
        /// </summary>
        debugger;
        "use strict";
        var combo = $("<select id='entityId'></select>");

        for (var cnt = 0; cnt < data.value.length; cnt++) {
            if (!data.value[cnt]["DisplayName"]["LocalizedLabels"][0]) {
                continue;
            }
            combo.append("<option value='" + data.value[cnt]["MetadataId"] + "'>" + data.value[cnt]["DisplayName"]["LocalizedLabels"][0]["Label"] + "</option>");

        }

        $("#dropDownEntities").append(combo);

        modelGeneration.BindEvents();
    },
    BindEvents: function () {
        /// <summary>
        /// Bind all  the HTML events
        /// </summary>
        "use strict";



        $("div.main-container .body-left").on("change", "#entityId", function () {
            modelGeneration.data.entityName = $(this).find("option:selected").text();
            BL.MG.FetchAttributeMetadata($(this).val(), modelGeneration.createModelFile, modelGeneration.errorHandler);

        })




    },

    createModelFile: function (data) {
        /// <summary>
        /// get all attributes for selected entity.
        /// </summary>
        "use strict";
        var tempData = data.LogicalName.toLowerCase() + "Model";

        var modelFile = '"use strict"\n';
        modelFile += 'var MK = MK || function(){};\n';
        modelFile += 'MK.ModelKit = MK.ModelKit || function(){};\n';
        modelFile += 'MK.ModelKit.' + data.LogicalName + ' = {};\n';
        modelFile += 'MK.ModelKit.Model = function () {\n';
        modelFile += '    "use strict";\n'
        modelFile += '    var ' + tempData + "={};\n";
        modelFile += '    if (!MK.ModelKit) {\n';
        modelFile += '    Xrm.Utility.alertDialog("MK.ModelKit is not present.");\n';
        modelFile += '    return;\n'
        modelFile += '    };\n';
        modelFile += '    MK.ModelKit.EntityProperty(' + tempData + ')\n';
        modelFile += '    ' + tempData + '.form = {};\n';
        modelFile += '    MK.ModelKit.UI.FormProperty(' + tempData + '.form)\n';
        modelFile += '    ' + tempData + '.fields = {};\n';
        modelFile += '    var fieldList = [];\n\n\n';
      
        for (var cnt = 0; cnt < data.Attributes.length;cnt++)
        {
            if (!data.Attributes[cnt].IsLogical) {
                modelFile += '    fieldList.push({ logicalname: "' + data.Attributes[cnt].LogicalName + '", type: "' + data.Attributes[cnt].AttributeType + '" });\n';
            }
        }
        modelFile += '    for (var i = 0; i < fieldList.length; i++) {\n';
        modelFile += '      ' + tempData + '.fields[fieldList[i].logicalname] = {};\n';
        modelFile += '         MK.ModelKit.FieldProperty(' + tempData + '.field[fieldList[i].logicalname],fieldList[i].logicalname, fieldList[i].type);\n';
        modelFile += '      }\n\n\n';
        modelFile += '    return ' + tempData + ';\n';
        modelFile += '}';
        var a = document.getElementById("a");
        var file = new Blob([modelFile], { type: "text/plain" });
        a.href = URL.createObjectURL(file);
        a.download = tempData+".js";

    },

    errorHandler: function (error) {
        "use strict";
        Xrm.Utility.alertDialog(error.message, null);
    },

}